package com.laogao.lesson037.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.TimeUnit;

/**
 * <b>description</b>： Java进阶、性能优化实战案例100讲，微信公众号:程序员恰恰，源码 & 文档 & 技术支持，请加个人微信号：it3306 <br>
 * <b>time</b>：2025/4/4 16:52 <br>
 * <b>author</b>：ready lao_gao
 * 如何使用 DeferredResult 实现异步请求处理。通过将耗时任务交给后台线程执行，可以有效提升系统的并发能力和响应速度。
 * http://localhost:8080/test
 */
@RestController
public class TestController {

    @GetMapping("/test")
    public DeferredResult<String> test() {
        System.out.println(Thread.currentThread());
        DeferredResult<String> deferredResult = new DeferredResult<>(2000000L, () -> {
            System.out.println(Thread.currentThread());
            return "timeout";
        });
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            deferredResult.setResult("ok");
        }).start();
        return deferredResult;
    }
}
